<template>
    <div class="print_item_form_container">
        <el-form ref="printItemForm" :rules="rules" :model="formData" label-width="80px">
            <el-form-item label="分组" prop="parent_sid" v-if="!isGroup">
                <el-select v-model="formData.parent_sid" placeholder="请选择分组" filterable
                           default-first-option style="width: 100%;">
                    <el-option v-for="(item, index) in groupList" :key="index"
                               :label="item.name" :value="item.sid" />
                </el-select>
            </el-form-item>
            <el-form-item label="类型" prop="cfg_type" v-if="!isGroup">
                <el-select v-model="formData.cfg_type" placeholder="请选择类型" filterable
                           default-first-option style="width: 100%;">
                    <el-option v-for="(item, index) in cfgTypeList" :key="index"
                               :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="名称" prop="name">
                <el-input v-model="formData.name" autocomplete="off" placeholder="请输入名称" />
            </el-form-item>
            <el-form-item :label="isGroup ? '编码' : '字段'" prop="code">
                <el-input v-model="formData.code" autocomplete="off" :placeholder="`请输入${ isGroup ? '编码' : '字段' }`" />
            </el-form-item>
            <el-form-item label="" v-if="!isGroup && ['text', 'longText'].indexOf(formData.cfg_type) !== -1">
                <el-checkbox v-model="formData.file" :true-label="1" :false-label="0">固定内容</el-checkbox>
            </el-form-item>
            <el-form-item label="固定内容" prop="note_info" v-if="!isGroup && formData.file === 1">
                <el-input v-model="formData.note_info" type="textarea" autocomplete="off"
                          maxlength="500" rows="4" show-word-limit placeholder="请输入固定内容" />
            </el-form-item>
            <el-form-item label="排序" prop="sn">
                <el-input v-model="formData.sn" autocomplete="off" placeholder="请输入排序，为空则自动排序" v-int />
            </el-form-item>
            <el-form-item label="列配置" prop="children" v-if="!isGroup && formData.cfg_type === 'table'">
                <vxe-table-template :data="dataList" :options.sync="tableOptions" />
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { mapState } from "vuex";
import UpDownFunction from "@common/utils/UpDownFunction";

export default {
    name: "PrintForm",
    props: {
        row: {
            type: Object,
            default: null,
        },
        groupList: {
            type: Array,
            default: () => [],
        },
        isGroup: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        const _this = this;
        return {
            rules: {
                parent_sid: [
                    { required: true, message: "请选择分组", trigger: "blur" },
                ],
                code: [
                    { required: true, message: `请输入${ _this.isGroup ? '编码' : '字段' }`, trigger: "blur" },
                    {
                        pattern: /^[A-Za-z0-9+-_.]{1,32}$/,
                        message:
                            "最大32位字符，大小写英文、数字或者以下特殊字符（+-_.），不能包含特殊字符",
                    },
                ],
                name: [
                    { required: true, message: "请输入名称", trigger: "blur" },
                    //目前只兼容中文、大小写英文、数字
                    {
                        // pattern: /^[A-Za-z0-9\u4e00-\u9fa5]{1,50}$/, message:'最大 50 位大小写英文、数字或者其它地区语言字符，不能包含特殊字符'
                        max: 50,
                        message: "最大 50 位字符，内容过长，请删减",
                        trigger: "blur",
                    },
                ],
                cfg_type: [
                    { required: true, message: "请选择类型", trigger: "blur" },
                ],
                note_info: [
                    { required: true, message: "请输入固定内容", trigger: "blur" },
                ],
            },
            formData: {},
            dataList: [],
            tableOptions: {
                ref: "$ColumnTable",
                editConfig: {
                    showStatus: true,
                },
                editRules: {
                    field: [
                        { required: true, message: '列字段必须填写' },
                        { pattern: /^[A-Za-z]{1}[A-Za-z0-9_]{0,31}$/, message: '最大32位字符，大小写英文开头，包含大小写英文、数字及特殊字符(_)' },
                    ],
                    text: [
                        { required: true, message: '列标题必须填写' },
                    ],
                },
                columns: [
                    {
                        label: "列字段",
                        prop: "field",
                        align: "center",
                        editRender: {
                            name: 'ElInput',
                            autofocus: 'input.el-input__inner',
                            autoselect: true,
                        },
                    },
                    {
                        label: "列标题",
                        prop: "text",
                        align: "center",
                        editRender: {
                            name: 'ElInput',
                            autofocus: 'input.el-input__inner',
                            autoselect: true,
                        },
                    },
                ],
                operates: {
                    list: [
                        {
                            id: "edit",
                            icon: "fa fa-plus",
                            size: "mini",
                            show: true,
                            tooltip: {
                                content: "下方插入",
                            },
                            method: (index, row) => {
                                _this.addRow(row);
                            },
                        },
                        {
                            id: 'up',
                            type: 'primary',
                            icon: 'el-icon-top',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '上移',
                            },
                            disabledFn(row) {
                                return row._index === 0;
                            },
                            method: (index, row) => {
                                _this.moveRow(row, -1);
                            }
                        },
                        {
                            id: 'down',
                            type: 'primary',
                            icon: 'el-icon-bottom',
                            size: 'mini',
                            show: true,
                            tooltip: {
                                content: '下移',
                            },
                            disabledFn(row) {
                                return row._index === _this.dataList.length - 1;
                            },
                            method: (index, row) => {
                                _this.moveRow(row, 1);
                            }
                        },
                    ],
                },
                getMaxHeight() {
                    let height = $(_this.getActiveTabsContainer()).height() * 0.8 - 200;
                    if (height < 100) {
                        height = 100;
                    }
                    return height;
                },
            },
        };
    },
    computed: {
        ...mapState('base', ['printTypeList', 'cfgTypeList']),
    },
    watch: {
        row: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init() {
            const _this = this;
            if (!_this.row) {
                return;
            }
            _this.dataList = [];
            if (!_this.$utils.isNotEmptyList(_this.printTypeList)) {
                await _this.$store.dispatch('base/initPrintTypeList');
            }
            if (_this.$refs.printItemForm) {
                _this.$refs.printItemForm.clearValidate();
            }
            _this.formData = $.extend({}, _this.row);
            if (_this.$utils.isNotEmpty(_this.formData.columns_json)) {
                _this.dataList = JSON.parse(_this.formData.columns_json);
            }
            if (!_this.$utils.isNotEmptyList(_this.dataList)) {
                _this.addRow(null);
            }
        },
        addRow(row) {
            const _this = this;
            let dataList = _this.dataList.map(item => $.extend({}, item));
            let addData = {
                field: '',
                text: '',
            };
            let index = _this.dataList.findIndex(item => row && item._index === row._index);
            if (index !== -1) {
                dataList.splice(index + 1, 0, addData);
            } else {
                dataList.push(addData);
            }
            _this.dataList = _this.resetIndex(dataList);
        },
        moveRow(row, type) {
            const _this = this;
            let dataList = _this.dataList.map(item => $.extend({}, item));
            let fun = new UpDownFunction(dataList, row._index);
            if (type === 1) {
                dataList = fun.downData();
            } else {
                dataList = fun.upData();
            }
            _this.dataList = _this.resetIndex(dataList);
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('printItemForm');
            if (valid) {
                if (_this.$ColumnTable) {
                    const errMap = await _this.$ColumnTable.validate().catch(errMap => errMap);
                    if (errMap) {
                        return false;
                    }
                }
                let subData = $.extend({}, _this.formData);
                let dataList = _this.dataList.map(item => {
                    return {
                        field: item.field,
                        text: item.text,
                        _index: item._index,
                    };
                });
                if (subData.cfg_type !== 'table') {
                    dataList = [];
                }
                subData.columns_json = JSON.stringify(dataList);
                return _this.fetchData(_this.$api.API_SaveBasePrintDesignItem, subData).then(() => {
                    _this.$message.success('保存成功！');
                    return true;
                }).catch(() => {
                    return false;
                });
            }
            return valid;
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.print_item_form_container {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
</style>
